<template>
    <ul class="sidebar-menu menuNoSet">
        <li class="treeNav slideTop" v-for="(item, index) in equipList" :key="index" :groupNo="item.groupId">
            <div class="link_box" @click.stop="showToggle($event,item)">
                <div class="parent_tag">
                    <span class="arrow">
                        <i class="iconfont iconyousanjiao arrowHide"></i>
                        <i class="iconfont iconxiasanjiao arrowShow"></i>
                    </span>
                    <label v-show="selectedMode === 0" :class="{'ivu-checkbox-inner': true, checkInput: true}" @click.stop.prevent="allEquipSel($event, 1)"></label>
                    <i class="iconfont icondian" :class="getClass(item.groupStatus)" v-if="!isCloseStatus"></i>
                    <a v-if="item.groupId === 1" href="javascript:void(0)" :class="{equipNoName: isCloseStatus}" :groupId="item.groupId">{{ $t('publics.platform') }}
                    </a>
                    <a v-else href="javascript:void(0)" :class="{equipNoName: isCloseStatus}" :groupId="item.groupId">{{ item.groupName }}
                    </a>
                    <!-- v-if="isOperation" -->
                    <div class="operation" @click.stop>
                        {{ item.count }}
                        <!-- <el-popover placement="bottom" trigger="hover">
                            <el-button-group class="new-button-group setModule">
                                <el-button type="primary text" class="elBtn" size="small" @click="newequip(item)">手动添加</el-button>
                                <el-button type="primary text" class="elBtn" size="small" @click="templateNewEquip(item)">模板添加</el-button>
                            </el-button-group>
                            <i class="iconfont icon16_tianjia" slot="reference"></i>
                        </el-popover>
                        <el-tooltip class="item" content="添加子分组" placement="top">
                            <i class="iconfont icontianjiafenzu" @click.stop="onAddEquipShow('新增分组', item)" v-if="item.groupId === 1"></i>
                        </el-tooltip>
                        <el-popover placement="bottom" trigger="hover" v-if="item.groupId !== 1">
                            <el-button-group class="new-button-group setModule">
                                <el-button type="text" size="small" class="elBtn" v-on:click.stop="onAddEquipShow('编辑分组', item)">重命名</el-button>
                                <el-button type="text" size="small" class="elBtn" @click="onAddEquipShow('新增分组', item)">添加子分组</el-button>
                                <el-button type="danger" size="small" v-on:click.stop="onDelFenZu(item, node + '-' + index)">删除</el-button>
                            </el-button-group>
                            <i class="el-icon-more" slot="reference"></i>
                        </el-popover> -->
                    </div>
                </div>
            </div>
            <ul>
                <template>
                    <li :class="{child_tags: true}" v-for="(equipChild, equipChild_id) in item.equipLists" :key="equipChild_id" v-if="equipChild.equipNo != 0" :equipNo="equipChild.equipNo">
                        <label v-show="selectedMode === 0" :class="{'ivu-checkbox-inner': true, checkInput: true}" @click.stop.prevent="radioEquipSel($event.target, 1,equipChild)" :no="equipChild.equipNo" :id="'no' + equipChild.equipNo" :staNo='equipChild.staNo'></label>
                        <i class="iconfont icondian equipNoNameChild" :class="getClass(equipChild.equipState)" v-if="!isCloseStatus" :data-no="equipChild.equipNo" :id="equipChild.equipNo"></i>
                        <a href="#" @click.stop.prevent="setEquipData(item,equipChild, $event)" :class="{equipNoName: isCloseStatus}">{{ equipChild.equipName }}
                        </a>
                        <!-- <el-popover placement="bottom" trigger="hover" v-if="isOperation">
                            <el-button type="text" size="small" class="elBtn" v-on:click.stop="setEquipModel(equipChild)">设为模板</el-button>
                            <el-button type="text" size="small" class="elBtn" v-on:click.stop="editEquip(equipChild)">编辑</el-button>
                            <el-button type="text" size="small" class="elBtn" v-on:click.stop="deleteEquip(item, equipChild)">删除</el-button>
                            <i class="el-icon-more" slot="reference"></i>
                        </el-popover> -->
                    </li>
                    <dynamicMenu :needRadioCheck='needRadioCheck' :radioCheck='radioCheck' v-if="item.children.length > 0" :equipSelected='equipSelected' :dataList="item.children" class="parentLevelTwoMenu" :isCloseStatus="isCloseStatus" :selectedMode="selectedMode" :selectedAll="selectedAll" :isOperation="isOperation" :isPage="isPage" :getItem="getItem" :node="node + '-' + index"></dynamicMenu>
                </template>
            </ul>
        </li>
    </ul>
</template>

<script>
import $ from 'jquery';
export default {
    name: 'dynamicMenu',
    props: {
        dataList: {
            type: Array,
            default: () => []
        },
        isOperation: {
            type: Boolean,
            default: false
        },
        isCloseStatus: {
            type: Boolean,
            default: false
        },
        isPage: {
            type: String,
            default: 'isPage'
        },
        selectedMode: {
            type: Number,
            default: 1
        },
        equipSelected: {
            type: Array,
            default: () => []
        },
        selectedAll: {
            type: Boolean,
            default: false
        },
        getItem: {
            type: Boolean | Function,
            default: () => []
        },
        node: {
            type: String,
            default: ''
        },
        radioCheck: {
            type: Function,
            default: () => { }
        },
        needRadioCheck: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            selected: '',
            pageNoLeft: 1,
            pageNum: 40,
            nodeLoad: true,
            totalLeft: 1,
            selectedEquip: [],
            equipList: [],
            saveItem: null,
            saveChildItem: null
        };
    },
    beforeRouteUpdate () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },

    // 更新data以及dom渲染之后
    updated () {
        let that = this;
        if (that.selectedAll) {
            $('.menuNoSet label').addClass('checkInput-active');
        }
        // $('.menuNoSet .slideTop>div')
        //     .unbind()
        //     .bind('click', function (e) {
        //         that.showToggle(this);
        //         e.stopPropagation();
        //     });
    },

    // 销毁前
    beforeDestroy () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },

    // 销毁完成
    destroyed () {
        let that = this;
        try {
            clearInterval(that.setInter);
        } catch (e) { }
    },
    computed: {
        getClass () {
            return function (state) {
                let className;
                switch (state) {
                    case 0:
                        className = 'NoCommunication';
                        break;
                    case 1:
                        className = 'CommunicationOK';
                        break;
                    case 2:
                        className = 'HaveAlarm';
                        break;
                    case 3:
                        className = 'HaveSetParm';
                        break;
                    case 4:
                        className = 'initial';
                        break;
                    case 5:
                        className = 'CheFang';
                        break;
                    case 6:
                        className = 'BackUp';
                        break;
                    default:
                        className = 'CommunicationOK';
                        break;
                }
                return className;
            };
        },
        initData () {
            return this.dataList;
        }
    },

    mounted () {

        // let that = this;
        // clearInterval(that.setInter);
        // that.setInter = setInterval(function () {
        //     if (that.selectedAll) {
        //         $('.menuNoSet label').addClass('checkInput-active');
        //     }
        //     if ($('.slideTop>div')) {
        //         clearInterval(that.setInter);
        //     }
        //     $('.menuNoSet .slideTop>div')
        //         .unbind()
        //         .bind('click', function (e) {
        //             that.showToggle(this);
        //             e.stopPropagation();
        //         });
        // }, 500);

        this.setSelected();

        // 初始化父类列表
        $('.sidebar-menu .HaveAlarm,.sidebar-menu .NoCommunication')
            .parents('ul')
            .prev('div.link_box')
            .find('i.icondian')
            .removeClass()
            .addClass('iconfont icondian HaveAlarm');
        this.equipList = JSON.parse(JSON.stringify(this.dataList));
        if (!this.isCloseStatus) {
            this.equipList = this.formateEquip(this.equipList);
        }
    },
    methods: {
        setSelected () {
            if (this.selectedMode === 0) {
                let result = this.equipSelected;
                $('.menuNoSet .checkInput-active').removeClass('checkInput-active');
                if (result.length > 0) {
                    let n = 0;
                    result.forEach((item, index) => {
                        let equipNo = '';
                        if (item.equipNo) {
                            equipNo = item.equipNo;
                        } else {
                            equipNo = item;
                        }

                        // let dom = '.menuNoSet [no = "' + parseInt(equipNo) + '"]';
                        this.radioEquipSel(`#no${equipNo}`, 2);

                        n++;
                        if (n == result.length) {

                            let isFlag = false,
                                ulDom = $('.checkInput-active').parents('ul:not(.sidebar-menu)'),
                                len = ulDom.length;

                            for (let i = 0; i < len; i++) {

                                // 判断不同结构的层级用不同的方式获取节点
                                isFlag = $(ulDom[i]).children('ul').length === 1 ? this.childrenCheckedNumber($(ulDom[i]).children('ul').children('li').children('div').find('label')) : this.childrenCheckedNumber($(ulDom[i]).find('label'));

                                if (isFlag) {
                                    $(ulDom[i])
                                        .prev('div')
                                        .find('label')
                                        .addClass('checkInput-active');
                                } else {
                                    $(ulDom[i])
                                        .prev('div')
                                        .find('label')
                                        .removeClass('checkInput-active');
                                }
                            }

                        }
                    });
                }
            } else {
                if (this.equipSelected.length > 0) {
                    $('.selectedColor').removeClass('selectedColor');
                    $(`[equipNo = '${this.equipSelected[0].equipNo}']`).addClass('selectedColor');
                }
            }
        },

        // 将报警设备往前排列
        formateEquip (list) {
            if (list && list.length > 0) {
                list.forEach((item, index) => {
                    let alarmList = [];
                    let noAlarmList = [];
                    let noCommunicationList = [];
                    if (item.equipLists && item.equipLists.length > 0) {
                        item.equipLists.forEach((childItem, index) => {
                            if (childItem.equipState === 2) {
                                alarmList.push(JSON.parse(JSON.stringify(childItem)));
                            } else if (childItem.equipState === 0) {
                                noCommunicationList.push(JSON.parse(JSON.stringify(childItem)));
                            } else {
                                noAlarmList.push(JSON.parse(JSON.stringify(childItem)));
                            }
                        });
                        item.equipLists = [...alarmList, ...noAlarmList, ...noCommunicationList];
                        if (alarmList.length > 0 || noCommunicationList.length > 0) {
                            item.groupStatus = 2;
                        } else {
                            item.groupStatus = 1;
                        }
                    }

                    if (item.children && item.children.length > 0) {
                        this.formateEquip(item.children);
                    }
                });
            }
            return list;
        },

        newequip (item) {
            this.$parent.newequip(item)
        },
        templateNewEquip (item) {
            this.$parent.templateNewEquip(item)
        },

        // 新增设备/分组-弹框
        onAddEquipShow (name, item) {
            this.$parent.onAddEquipShow(name, item);
        },

        // 删除分组
        onDelFenZu (item, node) {
            this.$parent.onDelFenZu(item, node);
        },

        // 删除设备
        deleteEquip (item, equipChild, node) {
            this.$parent.deleteEquip(item, equipChild, node);
        },

        // 不同形态设备选中
        setEquipData (item, equipChild, e) {
            this.saveItem = item;

            // this.saveChildItem = equipChild;
            $('.child_tags').removeClass('selectedColor');
            if (this.selectedMode === 1) {
                $(e.currentTarget)
                    .parent()
                    .addClass('selectedColor');
                if (typeof this.getItem === 'function') {

                    // 当需要选择设备控制项的时候传整个设备信息
                    this.getItem(equipChild, item);
                }
            } else {
                if (this.isPage === 'equipInfoPage') {
                    this.getItem(equipChild, item);
                }
                let dom = $(e.currentTarget)
                    .parent()
                    .children('label');
                this.radioEquipSel(dom, 1, equipChild);
            }
        },

        // 分组展开-关闭
        showToggle (dt, item) {

            if (
                $(dt.srcElement)
                    .parent().parent()
                    .hasClass('active')
            ) {
                $(dt.srcElement)
                    .parent().parent()
                    .removeClass('active');
            } else {
                if (item.count > 300) {
                    let equipListArray = [];
                    equipListArray = JSON.parse(JSON.stringify(item.equipLists))
                    item.equipLists = item.equipLists.slice(0, 1000)
                    setTimeout(() => {
                        item.equipLists = equipListArray
                    }, 200);
                    this.$forceUpdate()
                }
                $(dt.srcElement)
                    .parent().parent()
                    .addClass('active');
            }
        },

        // 分组全选
        allEquipSel (dt) {
            let isCheck = $(dt.target).hasClass('checkInput-active'),
                ulDom = $(dt.target).parents('ul'),
                len = ulDom.length,
                isFlag = true;
            if (isCheck) {
                $(dt.target).removeClass('checkInput-active');
                $(dt.target)
                    .parents('div.link_box')
                    .next()
                    .find('label.checkInput')
                    .removeClass('checkInput-active');
            } else {
                $(dt.target).addClass('checkInput-active');
                $(dt.target)
                    .parents('div.link_box')
                    .next()
                    .find('label.checkInput')
                    .addClass('checkInput-active');
            }
            if (
                !$(ulDom[0])
                    .parent()
                    .hasClass('equipList_main')
            ) {
                for (let i = 0; i < len; i++) {
                    isFlag = this.childrenCheckedNumber($(ulDom[i]).find('.checkInput'));
                    if (isFlag) {
                        $(ulDom[i])
                            .prev('div.link_box')
                            .find('label.checkInput')
                            .addClass('checkInput-active');
                    } else {
                        $(ulDom[i])
                            .prev('div.link_box')
                            .find('label.checkInput')
                            .removeClass('checkInput-active');
                    }
                }
            }
            this.equipInfoSelected();
        },

        // 设备选择
        radioEquipSel (that, n, equipChild) {
            let isCheck = $(that).hasClass('checkInput-active'),
                ulDom = $(that).parents('ul'),
                len = ulDom.length,
                isFlag = true;
            if (isCheck) {
                $(that).removeClass('checkInput-active');
            } else {
                $(that).addClass('checkInput-active');
            }

            if (this.isPage === 'dialog') {
                this.getItem(equipChild, isCheck);
            }

            if (n === 1) {
                for (let i = 0; i < len; i++) {

                    // isFlag = $(ulDom[i]).children('ul').length === 1 ? this.childrenCheckedNumber($(ulDom[i]).children('ul').children('li').children('div').find('label')) : this.childrenCheckedNumber($(ulDom[i]).find('label'));
                    isFlag = this.childrenCheckedNumber($(ulDom[i]).find('label'));
                    if (isFlag) {
                        $(ulDom[i])
                            .prev('div')
                            .find('label')
                            .addClass('checkInput-active');
                    } else {
                        $(ulDom[i])
                            .prev('div')
                            .find('label')
                            .removeClass('checkInput-active');
                    }
                }
            }

            if (this.needRadioCheck) {
                this.equipInfoSelected();
            }

            // this.equipInfoSelected();
        },

        childrenCheckedNumber (dt) {
            let len = dt.length,
                isFlag = true;
            for (let i = 0; i < len; i++) {
                isFlag = $(dt[i]).hasClass('checkInput-active');
                if (!isFlag) break;
            }
            return isFlag;
        },

        // 设备为模板
        setEquipModel (item) {
            this.$parent.setEquipModel(item);
        },

        // 编辑设备
        editEquip (item) {
            let isFlag = true,
                that = this,
                obj = '',
                n = 1;
            while (isFlag) {
                n++;
                if (!obj && n < 10) {
                    that = that.$parent;
                    try {
                        obj = that.init;
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    isFlag = false;
                }
            }
            if (n >= 10) {
                this.$message({
                    showClose: true,
                    message: '子菜单层级过深!',
                    type: 'warning'
                });
                return;
            }
            that.init(item.equipName, 'leftList');
        },

        // 选中设备号
        equipInfoSelected () {
            let arry = [],
                no = 0;
            if ($('.menuNoSet .checkInput-active')) {
                $('.menuNoSet .checkInput-active').each((index, item) => {
                    no = $(item).attr('no');
                    if (
                        no &&
                        !arry.some((itemChild, indeChild) => {
                            return no == itemChild;
                        })
                    ) {
                        arry.push(parseInt(no));
                    }
                });
            }
            this.$store.commit('setEquipInfo', arry);
            if (this.needRadioCheck) {
                this.radioCheck(arry)
            }

        }
    },
    watch: {
        equipSelected (newVal) {
            this.setSelected();
        },
        selectedAll (newVal) {
            if (newVal) {
                $('.menuNoSet label').addClass('checkInput-active');
            } else {
                $('.menuNoSet label').removeClass('checkInput-active');
            }
        },
        selectedMode (newVal) {
            console.log(newVal);
        },
        dataList: {
            handler (val, oval) {
                let that = this;
                // this.$nextTick(function () {
                //     $('.menuNoSet .slideTop>div')
                //         .unbind()
                //         .bind('click', function (e) {
                //             that.showToggle(this);
                //             e.stopPropagation();
                //         });
                // });
                this.setSelected();
                this.equipList = JSON.parse(JSON.stringify(this.dataList));
                if (!this.isCloseStatus) {
                    this.equipList = this.formateEquip(this.equipList);
                }
            },
            deep: true
        }
    }
};
</script>
<style lang="scss" src="./menu.scss" scoped></style>
